//
//  DateSelector.swift
//  aj
//
//  Created by leeqb on 2/11/16.
//  Copyright © 2016 powerlee. All rights reserved.
//

import UIKit

var g_dateSelector: DateSelector!

@objc protocol DateSelectorDelegate {
    func dateSelected(date: NSDate)
}

class DateSelector: NSObject {
    var delegate: DateSelectorDelegate!
    @IBOutlet var cntView: UIView!
    @IBOutlet weak var datePicker: UIDatePicker!
    
    override init() {
        super.init()
        
        self.initSelf()
    }
    
    private func initSelf() {
        LX("DateSelector", owner: self)
        
        self.cntView.frame.origin.y = SCREEN_HEIGHT
        self.cntView.frame.size.width = SCREEN_WIDTH
    }
    
    class func show(delegate: DateSelectorDelegate) {
        if g_dateSelector == nil {
            g_dateSelector = DateSelector()
        }
        
        g_dateSelector.delegate = delegate
        g_dateSelector.show()
    }
    
    private func show() {
        let keyWindow = UIApplication.sharedApplication().keyWindow
        keyWindow?.addSubview(self.cntView)
        
        UIView.animateWithDuration(0.3) { () -> Void in
            self.cntView.frame.origin.y = SCREEN_HEIGHT - self.cntView.frame.size.height
        }
    }
    
    func hide() {
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            self.cntView.frame.origin.y = SCREEN_HEIGHT
            }) { (completion: Bool) -> Void in
                self.cntView.removeFromSuperview()
        }
    }
    
    @IBAction func finishPick(sender: AnyObject) {
        self.hide()
        
        if delegate != nil {
            delegate.dateSelected(datePicker.date)
        }
    }
    
    @IBAction func dateChanged(sender: UIDatePicker) {
        
    }
    
}
